#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMenuBar>
#include <QMenu>
#include <QPlainTextEdit>
#include <QFileDialog>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("记事本");
    // 获取菜单栏
    QMenuBar *bar = this->menuBar();
    // 添加菜单
    QMenu *menu = new QMenu("文件",this);
    bar->addMenu(menu);
    // 添加菜单项
    QAction *action1 = new QAction("打开",menu);
    QAction *action2 = new QAction("保存",menu);
    menu->addAction(action1);
    menu->addAction(action2);

    // 指定一个输入框
    edit = new QPlainTextEdit(this);
    QFont font;
    font.setPixelSize(20);
    edit->setFont(font);

    this->setCentralWidget(edit);

    // 连接信号槽
    connect(action1,&QAction::triggered,this,&MainWindow::handle1);
    connect(action2,&QAction::triggered,this,&MainWindow::handle2);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handle1()
{
    // 先弹出 "打开文件" 对话框，让用户选择打开哪个文件
    const QString path = QFileDialog::getOpenFileName(this);
    // 把文件名显示到状态栏
    QStatusBar *statusBar = this->statusBar();
    statusBar->showMessage(path);
    // 打开文件
    QFile file(path);
    if(!file.open(QFile::ReadOnly))
    {
        statusBar->showMessage(path + "打开失败");
    }

    // 读取文件内容
    const QString test = file.readAll();

    // 关闭
    file.close();
    // 把内容放入输入框
    edit->setPlainText(test);
}

void MainWindow::handle2()
{
    // 先弹出 "保存文件" 对话框，让用户选择保存哪个文件
    const QString path = QFileDialog::getSaveFileName(this);
    // 把文件名显示到状态栏
    QStatusBar *statusBar = this->statusBar();
    statusBar->showMessage(path);
    // 打开文件
    QFile file(path);
    if(!file.open(QFile::WriteOnly))
    {
        statusBar->showMessage(path + "打开失败");
    }

    const QString test = edit->toPlainText();
    file.write(test.toUtf8());

    // 关闭文件
    file.close();
}


















